﻿package Classes.Maps{
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	import Classes.*;
	
	public class Maps {
		static public  const Grass:int = 1;
		static public  const Beach_Start:int = 2;
		static public  const Beach_End:int = 3;
		static public  const Hill:int = 4;
		static public  const Forest_End:int = 5;
		static public  const Forest_Start:int = 6;
		static public  const Sea:int = 7;

		static public  const tileWidth = GameSettings.tileWidth;
		static public  const tileHeight = GameSettings.tileHeight;
		static public  const sceneWidth:int = GameSettings.sceneWidth;
		static public  const sceneHeight:int = GameSettings.sceneHeight;
		static public  const numTile:int = GameSettings.numTile;

		private var bmpCrtBg:BitmapData;
		private var rect:Rectangle;
		private var crtTile:int;

		public var bmpBG:Bitmap;

		public var aMap:Array = [];
		
		public function Maps(map:Array) {
			aMap = map;
			crtTile = 0;
			bmpCrtBg = new BitmapData(tileWidth,tileHeight * numTile,false,0x000000);
			bmpBG = new Bitmap(new BitmapData(sceneWidth,sceneHeight));			
			rect = new Rectangle(0, 0, sceneWidth,sceneHeight);
			initMap();
		}
		
		public function scrollBg(scrollPos:int):void {
			var relativePos:int = scrollPos % tileHeight;
			var numTileRange:int = aMap.length - numTile;
			var rct:Rectangle = new Rectangle(0,tileHeight - relativePos,sceneWidth,sceneHeight);
			if(relativePos == 0){
				crtTile++;
				crtTile = crtTile > numTileRange ? numTileRange:crtTile;
				createTempMap();
			}
			bmpBG.bitmapData.copyPixels(bmpCrtBg, rct, new Point(0,0));
		}
		
		private function initMap():void{
			createTempMap();
			bmpBG.bitmapData.copyPixels(bmpCrtBg,
							new Rectangle(0,tileHeight,sceneWidth,sceneHeight),
							new Point(0,0));			
		}

		private function createTempMap():void {
			for (var i:int = 0; i<numTile; i++) {
				var tmpTile:BitmapData = getTileBmpData(aMap[crtTile + i]);
				bmpCrtBg.copyPixels(tmpTile, rect,new Point(0,sceneHeight-tileHeight*i));
				tmpTile.dispose();
				tmpTile = null;
			}
		}

		private function getTileBmpData(type:int):BitmapData {
			var bmpData:BitmapData;
			switch (type) {
				case Grass :
					bmpData = new BGrass(tileWidth,tileHeight);
					break;
				case Beach_Start :
					bmpData = new BGrass_Sea(tileWidth,tileHeight);
					break;
				case Beach_End :
					bmpData = new BSea_Grass(tileWidth,tileHeight);
					break;
				case Hill :
					bmpData = new BHill(tileWidth,tileHeight);
					break;
				case Forest_End :
					bmpData = new BForest_Grass(tileWidth,tileHeight);
					break;
				case Forest_Start :
					bmpData = new BGrass_Forest(tileWidth,tileHeight);
					break;
				case Sea :
					bmpData = new BSea(tileWidth,tileHeight);
					break;
				default :
					bmpData = new BGrass(tileWidth,tileHeight);
					break;
			}
			return bmpData;
		}
	}
}